package com.mark.springsecurity.controller;

import com.mark.springsecurity.domain.SysRole;
import com.mark.springsecurity.dto.req.SysRoleCmd;
import com.mark.springsecurity.dto.req.SysRoleQueryQbj;
import com.mark.springsecurity.dto.resp.MessageType;
import com.mark.springsecurity.dto.resp.Msg;
import com.mark.springsecurity.dto.resp.SysRoleDto;
import com.mark.springsecurity.service.RoleService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/roles")
public class RoleController {

    private final RoleService roleService;

    public RoleController(RoleService roleService) {
        this.roleService = roleService;
    }

    @PostMapping()
    public ResponseEntity<Msg<Object>> save(@RequestBody @Validated SysRoleCmd sysRoleCmd) {
        roleService.save(SysRoleCmd.buildSysRole(sysRoleCmd));
        Msg<Object> msg = new Msg<>(MessageType.MSG_TYPE_SUCCESS, null, null);
        return new ResponseEntity<>(msg, HttpStatus.OK);
    }

    @GetMapping("/list")
    public ResponseEntity<Msg<Page<SysRoleDto>>> list(SysRoleQueryQbj sysRoleQueryQbj, Pageable pageable) {
        Page<SysRoleDto> sysRoleDtoPage = SysRoleDto.buildListWithPage(sysUsers(sysRoleQueryQbj, pageable));
        Msg<Page<SysRoleDto>> msg = new Msg<>(MessageType.MSG_TYPE_SUCCESS, null, sysRoleDtoPage);
        return new ResponseEntity<>(msg, HttpStatus.OK);
    }

    private Page<SysRole> sysUsers(SysRoleQueryQbj sysRoleQueryQbj, Pageable pageable) {
        return roleService.findAll(SysRoleQueryQbj.buildExample(sysRoleQueryQbj), pageable);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Msg<SysRoleDto>> getOne(@PathVariable Long id) {
        Msg<SysRoleDto> msg = new Msg<>(MessageType.MSG_TYPE_SUCCESS, null, SysRoleDto.build(roleService.getOne(id)));
        return new ResponseEntity<>(msg, HttpStatus.OK);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Msg<Object>> update(@PathVariable Long id, @RequestBody SysRoleCmd sysRoleCmd) {
        roleService.update(id, sysRoleCmd);
        Msg<Object> msg = new Msg<>(MessageType.MSG_TYPE_SUCCESS, null, null);
        return new ResponseEntity<>(msg, HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Msg<Object>> delete(@PathVariable Long id) {
        roleService.delete(id);
        Msg<Object> msg = new Msg<>(MessageType.MSG_TYPE_SUCCESS, null, null);
        return new ResponseEntity<>(msg, HttpStatus.OK);
    }
}
